package jgl.vajra.management.widget;

import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;

/**
 * Created by Administrator on 2017/9/26.
 */

public class SearchRealTime implements CommonHandler.MessageHandler {

    private String currentWord;
    private SearchRealTimeFinishListener mListener;

    private MyRunnable myRunnable = new MyRunnable();

    private CommonHandler mHandler;
    private boolean cancelSendMessage = true;

    public void setPostDelayedTime(int postDelayedTime) {
        this.postDelayedTime = postDelayedTime;
    }

    public void resetPostDelayedTime() {
        setPostDelayedTime(postDelayedTime);
    }

    /**
     * 点击按钮响应间隔时间－毫秒
     */
    private int postDelayedTime = 2500;

    public SearchRealTime(Looper looper) {
        mHandler = new CommonHandler(looper, this);
    }

    /**
     * 这一步就是实时搜索优化的关键代码了，当EditText中的文字发生改变时，我们先会将handle中的Callback移除掉。然后使用Handle发一个延时的消息。最后通过回调getKeyword，让Activity开始搜索
     */
    public void realTimeSearch(String keyword) {
        if (TextUtils.isEmpty(keyword)) {
            return;
        }
        if (!cancelSendMessage) return;
        this.currentWord = keyword;
        if (myRunnable != null) {
            mHandler.removeCallbacks(myRunnable);
        }
        mHandler.postDelayed(myRunnable, postDelayedTime);
    }

    public void removeHandlerMessage() {
        mHandler.removeCallbacks(myRunnable);
    }

    public void setCancelSendMessage() {
        this.cancelSendMessage = false;
    }

    public void setCancelSendMessage(boolean cancelSendMessage) {
        this.cancelSendMessage = cancelSendMessage;
    }

    public void setSearchRealTimeFinishListener(SearchRealTimeFinishListener listener) {
        this.mListener = listener;
    }

    @Override
    public void handleMessage(Message msg) {
        if (mListener != null) {
            mListener.onQueryText(currentWord);
        }
    }


    public interface SearchRealTimeFinishListener {
        void onQueryText(String keyword);
    }

    private class MyRunnable implements Runnable {

        @Override
        public void run() {
            mHandler.sendEmptyMessage(1);
        }
    }

}

